<?php

namespace app\api\biz;

use app\common\biz\Biz;
use app\common\biz\list\Lists;
use app\common\biz\list\Search;
use app\common\Cache;
use app\common\enum\Cache as CacheEnum;
use app\common\enum\Code;
use app\common\enum\SearchType;
use app\common\model\biz\SysMenu;
use app\common\model\biz\SysRoleMenu;
use app\common\model\biz\SysUserRole;
use app\common\Result;
use Exception;
use think\db\exception\DbException;
use think\facade\Config;

class MenuBiz extends Biz
{

    public static function list(array $searchParams = [], bool $all = true): MenuBiz
    {
        $search = new Search($searchParams);
        $search->setPageSize(1000);
        $search->setOrder('sort', SearchType::OrderAsc->value);
        $search->setOrder('id', SearchType::OrderAsc->value);

        $lists = new Lists(new SysMenu(), $search);
        $data = SysMenu::tree($lists->lists(), 0, $all);

        return self::success(['list' => $data]);
    }

    public static function userList(): MenuBiz
    {
        $menu = [];
        $uid = Cache::get(CacheEnum::UID);
        $sysAdminIds = Config::get('admin.sys_user_id');
        if (in_array($uid, $sysAdminIds)) {
            //admin
            $menu = self::list()::getData();
            return self::success(['perms' => ['*'], 'menu' => $menu['list']]);
        }

        $userRole = SysUserRole::where('user_id', $uid)->select();
        if ($userRole->isEmpty()) {
            return self::success($menu);
        }
        $roleIds = array_column($userRole->toArray(), 'role_id');
        $userMenu = SysRoleMenu::whereIn('role_id', $roleIds)->select();
        if ($userMenu->isEmpty()) {
            return self::success($menu);
        }

        $menuIds = array_column($userMenu->toArray(), 'menu_id');
        $menuList = SysMenu::where('is_disable', 0)->select();
        $menu = SysMenu::treeByChildren($menuList->toArray(), $menuIds);
        $perms = [];
        foreach ($menu as $m) {
            if (empty($m['perms'])) {
                continue;
            }

            $perm = explode(',', $m['perms']);
            foreach ($perm as $p) {
                $perms[] = $p;
            }
        }
        $menu = SysMenu::tree($menu);
        SysMenu::sort($menu);

        return self::success(['perms' => $perms, 'menu' => $menu]);
    }

    public static function add(array $data): MenuBiz
    {
        try {
            if (3 == $data['type']) {
                $data['is_show'] = 0; //按钮不显示
            }
            $menu = SysMenu::create($data);
            return self::success($menu);
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }

    public static function edit(array $data): MenuBiz
    {
        if (!isset($data['id'])) {
            return self::errorByCode(Code::ParamsInvalid);
        }

        try {
            $menu = SysMenu::findOrEmpty($data['id']);
            if ($menu->isEmpty()) {
                return self::errorByCode(Code::DataNotFound);
            }

            if (3 == $data['type']) {
                $data['is_show'] = 0; //按钮不显示
            }
            $isOk = $menu->save($data);
            return self::success($isOk);
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }

    public static function del(string|array $ids): MenuBiz
    {
        $menu = SysMenu::whereIn('id', $ids)->select();
        if ($menu->isEmpty()) {
            return self::errorByCode(Code::DataNotFound);
        }

        foreach ($menu as $role) {
            $role->delete();
        }

        return self::success();

    }
}